<?php
/**
 * System_MenuController
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: UserMenuController.php 914 2011-10-26 09:40:18Z mmxie $
 */
class System_UserMenuController extends IG_Controller_Action
{

    public function listAction()
    {
        if ($this->getRequest()->isPost()) {
            $do = $this->_getParam('do');
            if (in_array($do, array('save', 'delete', 'move')))
                $this->{"_$do"}();
        }
        $menu = new System_Model_UserMenu();
        $this->view->assign(
            'data',
            $menu->fetchAll(
                    array('employee_id=?' => $this->getIdentity()->getEmployeeId()),
                    'position'
                 )
                 ->toArray()
        );
    }

    protected function _save()
    {
        $params = $this->_getParam('params');
        $menu = new System_Model_UserMenu($params);
        $menu->setEmployeeId($this->getIdentity()->getEmployeeId());
        $menu->save();
        $this->_helper->json(array('params' => $menu->toArray(), 'statusCode' => 0));
    }

    protected function _delete()
    {
        $id = $this->_getParam('id');
        $menu = new System_Model_UserMenu(array('id' => $id));
        $result = $menu->delete();
        $this->_helper->json(array('statusCode' => (int) !$result));
    }

    protected function _move()
    {
        $afterParent  = $this->_getParam('after_parent');
        $afterNode    = $this->_getParam('after_node');
        $beforeParent = $this->_getParam('before_parent');
        $current      = $this->_getParam('current');

        $menu = new System_Model_UserMenu();
        $afterNode = array_flip($afterNode);

        if (!empty($beforeParent)) {
            $menu->find($current)->setParentId($afterParent)->save();
        }

        foreach ($menu->fetchAll(array('parent_id=?' => $afterParent), 'position') as $key => $row) {
            if ($row->position == $afterNode[$row->id]) continue;
            $row->position = $afterNode[$row->id];
            $row->save();
        }

        $this->_helper->json(array('statusCode' => 0));
    }
}